<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script charset="utf-8" type="text/javascript" src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script charset="utf-8" type="text/javascript" src="/js/com.wxd.js"></script>
    <script charset="utf-8" type="text/javascript" src="/js/pageview.js"></script>
    <title>b</title>
    <link rel="stylesheet" type="text/css" href="/style/com.wxd.css"/>
    <link rel="stylesheet" type="text/css" href="/style/table.css"/>
    <style>
        .box {display: flex;flex-direction: column;}

        .root_box_top {height: 200px;}

        .root_box_center {flex: 1;}

        .root_box_bottom {height: 38px;}

        .root_box_bottom label {padding-left: 5px;padding-right: 5px;}

        .alertBoxBg .alertBox li {height: 23px;line-height: 20px;}

        .alertBoxBg .alertBox label {padding-left: 5px;padding-right: 5px;text-align: right;width: 80px;display: inline-block;}

        .alertBoxBg .alertBox input[type=text], .alertBoxBg .alertBox select {width: 180px;border: #8c8c8c 1px solid;}

    </style>
    <script>

        let pageView = null;

        function search() {
            wxd.loading();
            let urlQuery = new wxd.Map().loadSearch();
            urlQuery.put("minTime", $("#minTime").val());
            urlQuery.put("maxTime", $("#maxTime").val());
            urlQuery.put("where", $("#labWhere").text());
            urlQuery.put("order", $("#labOrderBy").text());
            pageView.remoteGetData(urlQuery);
        }

        // 用于显示的格式化版本
        function formatForDisplay(str) {
            if (typeof str === "string") {
                return str;
            }
            return JSON.stringify(str, null, 2); // 会保留换行和缩进
        }

        function formatJsonWithNewlines(obj) {
            if (typeof obj === 'string') {
                try {
                    obj = JSON.parse(obj);
                } catch (e) {
                    // 如果解析失败，直接格式化字符串
                    return obj;
                }
            }
            // 使用2个空格进行缩进，自动包含换行符
            return JSON.stringify(obj, null, 2);
        }

        function escapeJSString(str) {
            return formatForDisplay(str).replace(/\\/g, "\\\\")
                .replace(/'/g, "\\'")
                .replace(/"/g, "\\\"")
                .replace(/\n/g, "\\n")
                .replace(/\r/g, "\\r")
                .replace(/\t/g, "\\t");
        }

        function createRow(number, row, index) {
            // language=HTML
            let tr = `
                <tr ondblclick="alertShow(${index});">
                    <td style="width: 40px;">${number}</td>
                    <td style="width: 220px;">
                        <a href="#" onclick="gainCode(${row.uid}, 100)">生成100</a>
                        <a href="#" onclick="gainCode(${row.uid}, 1000)">生成1000</a>
                        <a href="#" onclick="queryCode(${row.uid})">获取</a>
                        <a href="#" onclick="editGiftCode(${row.uid},'${row.code}','${row.rewards}','${row.comment}','${row.validation}','${row.startTime}','${row.endTime}')">编辑</a>
                        <a href="#" onclick="delGiftCode(${row.uid})">删除</a>
                    </td>
                    <td>${row.uid}</td>
                    <td>${row.code}</td>
                    <td>${row.validation}</td>
                    <td>${row.rewards}</td>
                    <td>${row.comment}</td>
                    <td>${row.startTime}</td>
                    <td>${row.endTime}</td>
                </tr>
            `;
            return tr;
        }

        function alertShow(index) {
            let content = pageView.items[index];
            content = formatJsonWithNewlines(content);
            console.log("ddd", typeof content, content);
            new wxd.message.Alert(`<pre>${content}</pre>`, "详情").show();
        }

        $(() => {
            wxd.loading();
            let urlQuery = new wxd.Map().loadSearch();
            pageView = new PageView("/admin/giftcode/queryList", search, createRow);
            pageView.gameId = urlQuery.get("gameId");

            search();
        });

        let whereJsonArray = [];

        function addWhere() {
            let whereJson = {};
            whereJson["where"] = $("#where").val();
            whereJson["and"] = $("#and").val();
            whereJson["whereValue"] = $("#whereValue").val();
            whereJsonArray[whereJsonArray.length] = whereJson;
            $("#labWhere").text(JSON.stringify(whereJsonArray));
            $("#whereValue").val("")
            $("#and").val("=");
        }

        function clearWhere() {
            whereJsonArray = [];
            $("#labWhere").text("");
        }

        let orderByJsonArray = [];

        function addOrder() {
            let orderJson = {};
            orderJson["orderField"] = $("#orderField").val();
            orderJson["orderOption"] = $("#orderOption").val();
            orderByJsonArray[orderByJsonArray.length] = orderJson;
            $("#labOrderBy").text(JSON.stringify(orderByJsonArray));
        }

        function clearOrder() {
            orderByJsonArray = [];
            $("#labOrderBy").text("");
        }

        function gainCode(uid, num) {
            let param = "uid=" + uid + "&num=" + num;
            new wxd.netty.PostRequest("/admin/giftcode/gainCode", param, (data) => {
                if (data.code === 1) {
                    new wxd.message.Alert(formatForDisplay(data.data), "提示").show();
                } else {
                    wxd.message.notice(data.msg);
                }
            }).send();
        }

        function addValidation() {
            let text = $("#validation").text().trim();
            let v = ($("#validationKey").val() + "|let|" + $("#validationValue").val()).trim();
            if (wxd.isNull(text)) {
                $("#validation").text(v);
            } else {
                $("#validation").text(text + ";" + v);
            }
        }

        function editGiftCode(uid, code, rewards, comment, validation, startTime, endTime) {

            // language=HTML
            let ui = `
                <div>
                    <ul>
                        <li><label>UID:</label><span>${uid}</span></li>
                        <li>
                            <label for="code">礼包码:</label><input id="code" type="text" value="${code}">
                        </li>
                        <li>
                            <label for="rewards">奖励道具:</label><input id="rewards" type="text" value="${rewards}">
                        </li>
                        <li>
                            <label>限制条件:</label>
                            <select id="validationKey" style="width: 70px;">
                                <option value="DayCount">每日</option>
                                <option value="WeekCount">每周</option>
                                <option value="MonthCount">每月</option>
                                <option value="YearCount">每年</option>
                                <option value="ForeverCount">终身</option>
                            </select>
                            <input id="validationValue" type="text" style="width: 100px;" value="" placeholder="最大使用次数">
                            <input type="button" onclick="addValidation()" value="添加"/>
                            <input type="button" onclick="$('#validation').text('')" value="清理">
                        </li>
                        <li>
                            <span id="validation">${validation}</span>
                        <li>
                            <label for="comment">备注:</label><input id="comment" type="text" value="${comment}">
                        </li>
                        <li>
                            <label for="startTime">开始时间:</label><input id="startTime" type="datetime-local" value="${startTime}"/>
                        </li>
                        <li>
                            <label for="endTime">结束时间:</label><input id="endTime" type="datetime-local" value="${endTime}"/>
                        </li>
                    </ul>
                </div>
            `;

            let alertBox = new wxd.message.Alert(ui, "编辑礼包码");
            alertBox.okShow = "确认";
            alertBox.okCallback = () => {
                return new wxd.netty.PostRequest(
                    "/admin/giftcode/edit",
                    {
                        uid: uid,
                        code: $("#code").val(),
                        rewards: $("#rewards").val(),
                        validation: $("#validation").text(),
                        comment: $("#comment").val(),
                        startTime: $("#startTime").val(),
                        endTime: $("#endTime").val(),
                    },
                    (data) => {
                        wxd.message.notice(data.msg);
                        if (data.code === 1) {
                            search();
                            return true;
                        } else {
                            return false;
                        }
                    })
                    .async(false)
                    .send();
            };
            alertBox.show();
        }

        function delGiftCode(uid) {
            let param = "uid=" + uid;
            new wxd.netty.PostRequest("/admin/giftcode/del", param, (data) => {
                wxd.message.notice(data.msg);
                search();
            }).send();
        }

        function queryCode(uid) {
            let param = "uid=" + uid;
            new wxd.netty.PostRequest("/admin/giftcode/queryCode", param, (data) => {
                if (data.code === 1) {
                    new wxd.message.Alert(formatForDisplay(data.data), "提示").show();
                } else {
                    wxd.message.notice(data.msg);
                }
            }).send();
        }

    </script>
</head>
<body>
<div class="root box">
    <div class="root_box_top btn_box" style="padding-left: 20px; padding-top: 8px; text-align: left;vertical-align: center;">
        <label for="minTime">开始日期: </label><input id="minTime" type="date"/>
        <label for="maxTime">结束日期: </label><input id="maxTime" type="date"/>
        <br>
        <label for="where">查询条件:</label>
        <select id="where">
            <option value="id">id</option>
            <option value="code">code</option>
            <option value="comment">备注</option>
        </select>

        <select id="and" style="width: 60px;">
            <option value="=">=</option>
            <option value="<="><=</option>
            <option value="<"><</option>
            <option value=">=">>=</option>
            <option value=">">></option>
        </select>

        <input id="whereValue" type="text"/>
        <input type="button" onclick="addWhere();" value="添加"/>
        <input type="button" onclick="clearWhere();" value="清理"/>
        <br>
        <label for="labWhere">查询条件:</label><label id="labWhere"></label>
        <br>
        <label for="orderField">排序条件:</label>

        <select id="orderField">
            <option value="id">id</option>
            <option value="code">code</option>
            <option value="comment">备注</option>
        </select>

        <select id="orderOption" style="width: 60px;">
            <option value="DESC">降序</option>
            <option value="ASC">升序</option>
        </select>

        <input type="button" onclick="addOrder();" value="添加"/>
        <input type="button" onclick="clearOrder();" value="清理"/>
        <br>
        <label for="labOrderBy">排序条件:</label><label id="labOrderBy"></label>
        <br>
        <br>
        <button onclick="search();">查询</button>
        <button onclick="editGiftCode(0,'','','','','','','','');">新增</button>
    </div>
    <div class="root_box_center tableDom" style="margin: 10px; padding-right: 10px;border-radius: 0; overflow-x: auto;">
        <table>
            <thead>
            <tr>
                <th style="width: 40px;">编号</th>
                <th style="width: 220px;">操作</th>
                <th>ID</th>
                <th>通用码</th>
                <th>限制条件</th>
                <th>奖励</th>
                <th>备注</th>
                <th>开始时间</th>
                <th>结束时间</th>
            </tr>
            </thead>
            <tbody class="tbody">
            </tbody>
        </table>
    </div>
    <div class="root_box_bottom">
    </div>
</div>
</body>
</html>